class Pair < ActiveRecord::Base
	def p1
		p1 ||= Player.find self.p1_id
	end
	def p2
		p2 ||= Player.find self.p2_id
	end
	def self.randomize3(max=10)
old_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil
		i = 0
		(max/2).times do
			puts "MAX: #{i}" 		
			players = Player.all.sort_by{rand}
			while players.length > 1
				puts "PLAYER SIZE: #{players.length}"
				p1 = players.pop
				inner = players.select{|a| a.has_not_played(p1.id)}
				puts "INNER SIZE: #{inner.size}"
				p2 = inner.pop
				Pair.create(:p1_id => p1.id, :p2_id => p2.id)
			end
			i = i + 1
		end
ActiveRecord::Base.logger = old_logger
	end
	def self.randomize2(max=10)
		players = Player.all
		i = 0
		players.each do |p1|
			i = i + 1
			puts "Player: #{i}"
			from_list = Player.all.select{|a| a.id != p1.id && a.pairs.length < max}
			puts "from_list length: #{from_list.length}"
			from_list = from_list.sort_by{rand}
			if from_list.length >= (max - p1.pairs.length)
				(max - p1.pairs.length).times do 
					puts "looping: #{max - p1.pairs.length} times"
					p2 = from_list.pop
					Pair.create(:p1_id => p1.id, :p2_id => p2.id)
				end
			else
				puts "ERROR NOT ENOUGH PAIRS"
			end
		end
	end
	def self.randomize()
		players = Player.all
		while players.length > 0
			p1 = players.pop
			players.sort_by{rand}.each do |p2|
				Pair.create(:p1_id => p1.id, :p2_id => p2.id)
			end				
		end
	end
	def contains_id(id)
		return id == p1_id || id == p2_id
	end
	def contains_ids(id1, id2)
		return contains_id(id1) || contains_id(id2)
	end
	def contains_pair(pair)
		return contains_ids(pair.p1_id, pair.p2_id)
	end
	def game
		game ||= Game.where("pair1_id = ? OR pair2_id = ?", id, id)[0]
	end
	def opponent
		if game.pair1_id == id
			opponent ||= Pair.find(game.pair2_id)
		else
			opponent ||= Pair.find(game.pair1_id)
		end
	end
	def played
		played = (updated_at > created_at)
	end
end
